package com.lucenex.core;

import java.io.IOException;

import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;

import com.lucenex.bean.BeanConfig;
import com.lucenex.dic.lucene.LDAnalyzer;
import com.lucenex.util.OpenLuceneSource;

import lombok.Builder;

/**
 * 核心控制类
 * @author zxw
 *
 */
@Builder
public class LuceneX {

	private static LuceneDataSource source;

	/**
	 * 添加源
	 * @param dataSourceKey
	 * @param luceneXConfig
	 * @throws IOException
	 */
	public void add(String dataSourceKey,LuceneXConfig luceneXConfig) throws IOException {
		//设置默认分词器
		luceneXConfig.setAnalyzer(luceneXConfig.getAnalyzer() == null ? new PerFieldAnalyzerWrapper(new LDAnalyzer(dataSourceKey)) : luceneXConfig.getAnalyzer());
		luceneXConfig.setWriter(
				OpenLuceneSource.builder()
				.indexPath(luceneXConfig.getIndexPath()+dataSourceKey)
				.analyzer(luceneXConfig.getAnalyzer())
				.build()
				.indexWriter());
		luceneXConfig.setSearcher(OpenLuceneSource.builder().build().dynamicIndexSearcher(luceneXConfig.getWriter()));
		source.setDataSource(dataSourceKey, luceneXConfig);
	}

	/**
	 * 启动器
	 * @param className
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static void start(String className) throws InstantiationException, IllegalAccessException, IOException, ClassNotFoundException{
		Class<?> clas = Class.forName(className);
		source = LuceneDataSource.build();
		CoreConfig newInstance = (CoreConfig) clas.newInstance();
		//实例化bean
		newInstance.configPlugin(BeanConfig.build());
		//实例化数据源
		newInstance.configLuceneX(LuceneX.builder().build());
		//启动自动回收站
		DoShutDownWork.build();
	}
	
	public static void start(Class<?> coreConfig) throws IOException, InstantiationException, IllegalAccessException {
		source = LuceneDataSource.build();
		CoreConfig newInstance = (CoreConfig) coreConfig.newInstance();
		newInstance.configPlugin(BeanConfig.build());
		//实例化数据源
		newInstance.configLuceneX(LuceneX.builder().build());
		//启动自动回收站
		DoShutDownWork.build();
	}

	/**
	 * 手动提交数据
	 * @throws IOException
	 */
	public static void submit() throws IOException {
		source.submit();
	}
}
